#! /bin/sh
function kill_bemc_ps()
{
	ps_file=ps${RANDOM}.file
	ps -aef | grep -i java | awk '{print $2}' | grep -P "\\d+" > ${ps_file}
	bt_ps_count=0
	while read line || [[ -n ${line} ]]
	  do
	  if [[ $line -ne $$ ]]; then
		path=`pwdx $line 2>/dev/null | awk '{print $NF}'`
		if [[ "$path" =~ ^${btcloud_home}.* ]];then
			kill -9 $line > /dev/null 2>&1
		fi
	  fi
	done  < ${ps_file}
	rm -f ${ps_file}
}

echo "是否确认卸载，如果不确定， 请Ctrl+C退出执行本脚本"
read -s -n1 -p "否则， 按回车键开始卸载"
echo

#读取一下环境变量，防止出现变量拿不到的情况
source /etc/profile

while true
do
	launch2status=`systemctl status launch2.service | grep -Po "Active:\\s*\K[^\\s]+"`
	
	if [[ -z "$launch2status" && -z "$btcloud_home" ]];then
		echo "未安装产品！"
		exit 1
	fi
	
	if [[ "$launch2status" = "active" ]]; then
		echo "正在停止服务..."
		systemctl stop launch2.service
	else
		echo "服务已停止"
		echo
		break
	fi
done

#把进程都杀死
kill_bemc_ps

which systemctl 1>/dev/null 2>/dev/null
# 0 is ok
if [ $? -ne 0 ]
then
	chkconfig launch2 off
	chkconfig --del launch2 > /dev/null 2>&1
	service launch2 stop
	rm -f /etc/init.d/launch2 > /dev/null 2>&1
else
	systemctl stop launch2.service
	systemctl disable launch2.service > /dev/null 2>&1
	rm -f /usr/lib/systemd/system/launch2.service > /dev/null 2>&1
fi
let retry=1
while true
do
	if [ $retry -eq 1 ];then
		echo "开始删除目录："$btcloud_home
	fi
	
	if [ -e $btcloud_home ];then
		retry=0
		rm -rf $btcloud_home > /dev/null 2>&1
	else
		echo "目录已清空："$btcloud_home
		break
	fi
done

#删除dgo数据库的临时文件
rm -f /tmp/.s.PGSQL.30903
rm -f /tmp/.s.PGSQL.30903.lock
#删除nacos的缓存数据
rm -rf /root/nacos/config/*30000_nacos > /dev/null 2>&1

#删除/etc/profile 中的环境变量配置
sed -i '/export btcloud_home=/d' /etc/profile
sed -i '/export JAVA_HOME=\/opt\/Betasoft\/base\/jre/d' /etc/profile
sed -i '/export PATH=$JAVA_HOME\/bin:$PATH/d' /etc/profile
sed -i '/export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:\/opt\/Betasoft\/base\/pgsql\/lib:./d' /etc/profile
sed -i '/export btso_home=/d' /etc/profile
sed -i '/export BTSO_HOME=/d' /etc/profile

echo "卸载完成！"